package org.example.infrastructure.persistent.repository;

import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.activity.event.ActivitySkuStockZeroMessageEvent;
import org.example.domain.activity.model.arrtrgate.CreatePartakeOrderAggregate;
import org.example.domain.activity.model.arrtrgate.CreateQuotaOrderAggregate;
import org.example.domain.activity.model.entity.*;
import org.example.domain.activity.model.valobj.ActivitySkuStockKeyVO;
import org.example.domain.activity.model.valobj.ActivityStateVO;
import org.example.domain.activity.model.valobj.userRaffleOrderStateVO;
import org.example.domain.activity.repository.IActivityRepository;
import org.example.infrastructure.event.EventPublish;
import org.example.infrastructure.persistent.dao.*;
import org.example.infrastructure.persistent.po.*;
import org.example.infrastructure.persistent.redis.IRedisService;
import org.example.types.common.Constants;
import org.example.types.enums.ResponseCode;
import org.example.types.exception.AppException;
import org.redisson.api.RBlockingQueue;
import org.redisson.api.RDelayedQueue;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ActivityRepository implements IActivityRepository {
    @Resource
    private IRaffleActivitySkuDao raffleActivitySkuDao;
    @Resource
    private IRaffleActivityDao raffleActivityDao;
    @Resource
    private IRaffleActivityCountDao raffleActivityCountDao;
    @Resource
    private IRedisService redisService;
    @Resource
    private IDBRouterStrategy dbRouter;
    @Resource
    private TransactionTemplate transactionTemplate;
    @Resource
    private IRaffleActivityOrderDao raffleActivityOrderDao;
    @Resource
    private IRaffleActivityAccountDao raffleActivityAccountDao;
    @Resource
    private EventPublish eventPublish;
    @Resource
    private ActivitySkuStockZeroMessageEvent activitySkuStockZeroMessageEvent;
    @Resource
    private IRaffleActivityAccountDayDao raffleActivityAccountDayDao;
    @Resource
    private IRaffleActivityAccountMonthDao raffleActivityAccountMonthDao;
    @Resource
    private IUserRaffleOrderDao userRaffleOrderDao;
    @Override
    public ActivitySkuEntity queryActivitySkuEntityBysku(Long sku) {
        String cachekey = Constants.RedisKey.ACTIVITY_SKU_KEY + sku;
        if (redisService.isExists(cachekey)) return redisService.getValue(cachekey);
        ActivitySkuEntity activitySkuEntity = new ActivitySkuEntity();
        if (null == sku) {
            log.error("查询活动sku实体失败,sku检查为空");
            return null;
        }
        RaffleActivitySku raffleActivitySku = raffleActivitySkuDao.queryActivitySku(sku);
        activitySkuEntity.setSku(raffleActivitySku.getSku());
        activitySkuEntity.setActivityId(raffleActivitySku.getActivityId());
        activitySkuEntity.setActivityCountId(raffleActivitySku.getActivityCountId());
        activitySkuEntity.setStockCount(raffleActivitySku.getStockCount());
        activitySkuEntity.setStockCountSurplus(raffleActivitySku.getStockCountSurplus());
        redisService.setValue(cachekey,activitySkuEntity);
        return activitySkuEntity;
    }

    @Override
    public ActivityEntity queryActivityEntityByactivityId(Long activityId) {
        String cachekey = Constants.RedisKey.ACTIVITY_KEY + activityId;
        if (redisService.isExists(cachekey)) return redisService.getValue(cachekey);
        ActivityEntity activityEntity = new ActivityEntity();
        if (null == activityId) {
            log.error("查询活动实体失败,activityId检查为空");
            return null;
        }
        RaffleActivity raffleActivity = raffleActivityDao.queryRaffleActivityByActivityId(activityId);
        activityEntity.setActivityId(raffleActivity.getActivityId());
        activityEntity.setActivityName(raffleActivity.getActivityName());
        activityEntity.setActivityDesc(raffleActivity.getActivityDesc());
        activityEntity.setBeginDateTime(raffleActivity.getBeginDateTime());
        activityEntity.setEndDateTime(raffleActivity.getEndDateTime());
        activityEntity.setStrategyId(raffleActivity.getStrategyId());
        activityEntity.setState(ActivityStateVO.valueOf(raffleActivity.getState()) );
        redisService.setValue(cachekey,activityEntity);
        return activityEntity;
    }

    @Override
    public ActivityCountEntity queryRaffleActivityCountByActivityCountId(Long activityCountId) {
        String cachekey = Constants.RedisKey.ACTIVITY_COUNT_KEY + activityCountId;
        if (redisService.isExists(cachekey)) return redisService.getValue(cachekey);
        ActivityCountEntity activityCountEntity = new ActivityCountEntity();
        if (null == activityCountId) {
            log.error("查询活动次数实体失败,activityCountId检查为空");
            return null;
        }
        RaffleActivityCount raffleActivityCount = raffleActivityCountDao.queryRaffleActivityCountByActivityCountId(activityCountId);
        activityCountEntity.setActivityCountId(raffleActivityCount.getActivityCountId());
        activityCountEntity.setTotalCount(raffleActivityCount.getTotalCount());
        activityCountEntity.setDayCount(raffleActivityCount.getDayCount());
        activityCountEntity.setMonthCount(raffleActivityCount.getMonthCount());
        return activityCountEntity;

    }

    @Override
    public void doSaveOrder(CreateQuotaOrderAggregate createQuotaOrderAggregate) {

        try{
            ActivityOrderEntity activityOrderEntity = createQuotaOrderAggregate.getActivityOrderEntity();
            RaffleActivityOrder activityOrder = new RaffleActivityOrder();
             activityOrder.setUserId(activityOrderEntity.getUserId());
             activityOrder.setSku(activityOrderEntity.getSku());
             activityOrder.setActivityId(activityOrderEntity.getActivityId());
             activityOrder.setActivityName(activityOrderEntity.getActivityName());
             activityOrder.setStrategyId(activityOrderEntity.getStrategyId());
             activityOrder.setOrderId(activityOrderEntity.getOrderId());
             activityOrder.setOrderTime(activityOrderEntity.getOrderTime());
             activityOrder.setTotalCount(activityOrderEntity.getTotalCount());
             activityOrder.setDayCount(activityOrderEntity.getDayCount());
             activityOrder.setMonthCount(activityOrderEntity.getMonthCount());
             activityOrder.setState(activityOrderEntity.getState().getCode());
             activityOrder.setOutBusinessNo(activityOrderEntity.getOutBusinessNo());


            //用户总账户
            RaffleActivityAccount raffleActivityAccount = new RaffleActivityAccount();
             raffleActivityAccount.setUserId(createQuotaOrderAggregate.getUserId());
             raffleActivityAccount.setActivityId(createQuotaOrderAggregate.getActivityId());
             raffleActivityAccount.setTotalCount(createQuotaOrderAggregate.getTotalCount());
             raffleActivityAccount.setTotalCountSurplus(createQuotaOrderAggregate.getTotalCount());
             raffleActivityAccount.setDayCount(createQuotaOrderAggregate.getDayCount());
            raffleActivityAccount.setDayCountSurplus(createQuotaOrderAggregate.getDayCount());
             raffleActivityAccount.setMonthCount(createQuotaOrderAggregate.getMonthCount());
             raffleActivityAccount.setMonthCountSurplus(createQuotaOrderAggregate.getMonthCount());

             //用户月账户
            RaffleActivityAccountMonth raffleActivityAccountMonth = new RaffleActivityAccountMonth();
             raffleActivityAccountMonth.setUserId(createQuotaOrderAggregate.getUserId());
             raffleActivityAccountMonth.setActivityId(createQuotaOrderAggregate.getActivityId());
             raffleActivityAccountMonth.setMonth(raffleActivityAccountMonth.currentMonth());
             raffleActivityAccountMonth.setMonthCount(createQuotaOrderAggregate.getMonthCount());
             raffleActivityAccountMonth.setMonthCountSurplus(createQuotaOrderAggregate.getMonthCount());
             //用户日账户
            RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay();
             raffleActivityAccountDay.setUserId(createQuotaOrderAggregate.getUserId());
             raffleActivityAccountDay.setActivityId(createQuotaOrderAggregate.getActivityId());
             raffleActivityAccountDay.setDay(raffleActivityAccountDay.currentDate());
             raffleActivityAccountDay.setDayCount(createQuotaOrderAggregate.getDayCount());
             raffleActivityAccountDay.setDayCountSurplus(createQuotaOrderAggregate.getDayCount());

            dbRouter.doRouter(createQuotaOrderAggregate.getUserId());
            transactionTemplate.execute(status -> {
                try {
                    //插入订单
                    raffleActivityOrderDao.insert(activityOrder);
                    //更新账户
                    int count = raffleActivityAccountDao.updateAccountQuota(raffleActivityAccount);
                    if (0 == count){
                        raffleActivityAccountDao.insert(raffleActivityAccount);
                    }
                    // 4. 更新账户 - 月
                    raffleActivityAccountMonthDao.addAccountQuota(raffleActivityAccountMonth);
                    // 5. 更新账户 - 日
                    raffleActivityAccountDayDao.addAccountQuota(raffleActivityAccountDay);
                    return 1;
                }catch (DuplicateKeyException e){
                    status.setRollbackOnly();
                    log.error("写入订单记录，唯一索引冲突 userId: {} activityId: {} sku: {}", activityOrderEntity.getUserId(), activityOrderEntity.getActivityId(), activityOrderEntity.getSku(), e);
                    throw new AppException(ResponseCode.INDEX_DUP.getCode());
                }

            });
        }finally {
            dbRouter.clear();
        }

    }
    @Override
    public boolean subtractionActivitySkuStock(Long sku,String cacheKey) {
        return subtractionActivitySkuStock(sku,cacheKey,null);
    }



    @Override
    public boolean subtractionActivitySkuStock(Long sku,String cacheKey , Date activityEndTime) {
        long surplus = redisService.decr(cacheKey);
        if (0 == surplus){
            eventPublish.publish(activitySkuStockZeroMessageEvent.topic(),activitySkuStockZeroMessageEvent.buildEventMessage(sku));
            return false;
        }else if(surplus < 0){
            redisService.setAtomicLong(cacheKey,0);
        }
        String lockKey = cacheKey + Constants.UNDERLINE + surplus;
        long expireMillis = activityEndTime.getTime() - System.currentTimeMillis() + TimeUnit.DAYS.toMillis(1);
        Boolean lock = redisService.setNx(lockKey, expireMillis, TimeUnit.MILLISECONDS);
        if (!lock){
            log.info("活动sku库存加锁失败 {}", lockKey);
        }
        return lock;
    }
    @Override
    public void activitySkuStockAddConsumeSendQueue(ActivitySkuStockKeyVO build) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY;
        RBlockingQueue<ActivitySkuStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey);
        RDelayedQueue<ActivitySkuStockKeyVO> delayedQueue = redisService.getDelayedQueue(blockingQueue);
        delayedQueue.offer(build, 3, TimeUnit.SECONDS);
    }

    @Override
    public ActivitySkuEntity queryActivitySku(Long sku) {
        RaffleActivitySku raffleActivitySku = raffleActivitySkuDao.queryActivitySku(sku);
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        Long cacheSkuStock = redisService.getAtomicLong(cacheKey);
        if (null == cacheSkuStock || 0 == cacheSkuStock) {
            cacheSkuStock = 0L;
        }
        return ActivitySkuEntity.builder()
                .sku(raffleActivitySku.getSku())
                .activityId(raffleActivitySku.getActivityId())
                .activityCountId(raffleActivitySku.getActivityCountId())
                .stockCount(raffleActivitySku.getStockCount())
                .stockCountSurplus(cacheSkuStock.intValue())
                .build();

    }

    @Override
    public ActivityEntity queryRaffleActivityByActivityId(Long activityId) {
        // 优先从缓存获取
        String cacheKey = Constants.RedisKey.ACTIVITY_KEY + activityId;
        ActivityEntity activityEntity = redisService.getValue(cacheKey);
        if (null != activityEntity) return activityEntity;
        // 从库中获取数据
        RaffleActivity raffleActivity = raffleActivityDao.queryRaffleActivityByActivityId(activityId);
        activityEntity = ActivityEntity.builder()
                .activityId(raffleActivity.getActivityId())
                .activityName(raffleActivity.getActivityName())
                .activityDesc(raffleActivity.getActivityDesc())
                .beginDateTime(raffleActivity.getBeginDateTime())
                .endDateTime(raffleActivity.getEndDateTime())
                .strategyId(raffleActivity.getStrategyId())
                .state(ActivityStateVO.valueOf(raffleActivity.getState()))
                .build();
        redisService.setValue(cacheKey, activityEntity);
        return activityEntity;


    }

    @Override
    public void cacheActivitySkuStockCount(String cacheKey, Integer stockCount) {
        if (redisService.isExists(cacheKey)) return;
        redisService.setAtomicLong(cacheKey, stockCount);

    }

    @Override
    public ActivitySkuStockKeyVO takeQueueValue() {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY;
        RBlockingQueue<ActivitySkuStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey);
        return blockingQueue.poll();
    }

    @Override
    public void clearQueueValue() {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY;
        RBlockingQueue<ActivitySkuStockKeyVO> blockingQueue = redisService.getBlockingQueue(cacheKey);
        blockingQueue.clear();
    }

    @Override
    public void updateActivitySkuStock(Long sku) {
        raffleActivitySkuDao.updateActivitySkuStock(sku);
    }

    @Override
    public void clearActivitySkuStock(Long sku) {
        raffleActivitySkuDao.clearActivitySkuStock(sku);
    }

    @Override
    public void savecreatePartakeOrderAggregate(CreatePartakeOrderAggregate createPartakeOrderAggregate) {
        try {
            String userId = createPartakeOrderAggregate.getUserId();
            Long activityId = createPartakeOrderAggregate.getActivityId();
            UserRaffleOrderEntity userRaffleOrderEntity = createPartakeOrderAggregate.getUserRaffleOrderEntity();
            ActivityAccountEntity activityAccountEntity = createPartakeOrderAggregate.getActivityAccountEntity();
            ActivityAccountDayEntity activityAccountDayEntity = createPartakeOrderAggregate.getActivityAccountDayEntity();
            ActivityAccountMonthEntity activityAccountMonthEntity = createPartakeOrderAggregate.getActivityAccountMonthEntity();

            dbRouter.doRouter(userId);
            transactionTemplate.execute(status -> {

                try {
                 RaffleActivityAccount raffleActivityAccount = new RaffleActivityAccount();
                 raffleActivityAccount.setUserId(activityAccountEntity.getUserId());
                 raffleActivityAccount.setActivityId(activityAccountEntity.getActivityId());
                 raffleActivityAccount.setTotalCount(activityAccountEntity.getTotalCount());
                 raffleActivityAccount.setTotalCountSurplus(activityAccountEntity.getTotalCountSurplus());
                 raffleActivityAccount.setDayCount(activityAccountEntity.getDayCount());
                 raffleActivityAccount.setDayCountSurplus(activityAccountEntity.getDayCountSurplus());
                 raffleActivityAccount.setMonthCount(activityAccountEntity.getMonthCount());
                 raffleActivityAccount.setMonthCountSurplus(activityAccountEntity.getMonthCountSurplus());

                 int count =  raffleActivityAccountDao.updateActivityAccountSubtractionQuota(raffleActivityAccount);
                  if (1 != count){
                      status.setRollbackOnly();
                      log.warn("写入创建参与活动记录，更新总账户额度不足，异常 userId: {} activityId: {}", userId, activityId);
                      throw new AppException(ResponseCode.ACCOUNT_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_QUOTA_ERROR.getInfo());
                  }
                   RaffleActivityAccountMonth raffleActivityAccountMonth = new RaffleActivityAccountMonth();
                   raffleActivityAccountMonth.setUserId(activityAccountMonthEntity.getUserId());
                   raffleActivityAccountMonth.setActivityId(activityAccountMonthEntity.getActivityId());
                   raffleActivityAccountMonth.setMonth(activityAccountMonthEntity.getMonth());
                   raffleActivityAccountMonth.setMonthCount(activityAccountMonthEntity.getMonthCount());
                   raffleActivityAccountMonth.setMonthCountSurplus(activityAccountMonthEntity.getMonthCountSurplus());
                    if (createPartakeOrderAggregate.isExistAccountMonth()) {
                        int countMonth = raffleActivityAccountMonthDao.updateActivityMonthAccountSubtractionQuota(raffleActivityAccountMonth);
                        if (1 != countMonth) {
                            status.setRollbackOnly();
                            log.warn("写入创建参与活动记录，更新月账户额度不足，异常 userId: {} activityId: {}", userId, activityId);
                            throw new AppException(ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_MONTH_QUOTA_ERROR.getInfo());
                        }
                    }
                    else {
                        raffleActivityAccountMonth.setMonthCountSurplus(raffleActivityAccountMonth.getMonthCountSurplus()-1);
                        raffleActivityAccountMonthDao.insertActivityMonthAccount(raffleActivityAccountMonth);
                    }
                    RaffleActivityAccountDay raffleActivityAccountDay = new RaffleActivityAccountDay();
                    raffleActivityAccountDay.setUserId(activityAccountDayEntity.getUserId());
                    raffleActivityAccountDay.setActivityId(activityAccountDayEntity.getActivityId());
                    raffleActivityAccountDay.setDay(activityAccountDayEntity.getDay());
                    raffleActivityAccountDay.setDayCount(activityAccountDayEntity.getDayCount());
                    raffleActivityAccountDay.setDayCountSurplus(activityAccountDayEntity.getDayCountSurplus());
                    if (createPartakeOrderAggregate.isExistAccountDay()){
                        int countDay = raffleActivityAccountDayDao.updateActivityDayAccountSubtractionQuota(raffleActivityAccountDay);
                        if (1 != countDay){
                            status.setRollbackOnly();
                            log.warn("写入创建参与活动记录，更新日账户额度不足，异常 userId: {} activityId: {}", userId, activityId);
                            throw new AppException(ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getCode(), ResponseCode.ACCOUNT_DAY_QUOTA_ERROR.getInfo());
                        }
                    }
                    else {
                        raffleActivityAccountDay.setDayCountSurplus(activityAccountEntity.getDayCountSurplus()-1);
                        raffleActivityAccountDayDao.insertActivityAccountDay(raffleActivityAccountDay);
                    }
                     UserRaffleOrder userRaffleOrder = new UserRaffleOrder();
                     userRaffleOrder.setUserId(userRaffleOrderEntity.getUserId());
                     userRaffleOrder.setActivityId(userRaffleOrderEntity.getActivityId());
                     userRaffleOrder.setActivityName(userRaffleOrderEntity.getActivityName());
                     userRaffleOrder.setStrategyId(userRaffleOrderEntity.getStrategyId());
                     userRaffleOrder.setOrderId(userRaffleOrderEntity.getOrderId());
                     userRaffleOrder.setOrderTime(userRaffleOrderEntity.getOrderTime());
                     userRaffleOrder.setOrderState(userRaffleOrderEntity.getOrderState().getCode());

                     userRaffleOrderDao.insert(userRaffleOrder);
                     return 1;
                }catch (DuplicateKeyException e){
                    status.setRollbackOnly();
                    log.error("写入创建参与活动记录,唯一索引冲突,userId:{} activityId:{}",userId,activityId);
                    throw new AppException(ResponseCode.INDEX_DUP.getCode(),e);
                }

            });
        }finally {
            dbRouter.clear();
        }
    }

    @Override
    public UserRaffleOrderEntity queryNoUsedRaffleOrder(PartakeRaffleActivityEntity partakeRaffleActivityEntity) {
        // 查询数据
        UserRaffleOrder userRaffleOrderReq = new UserRaffleOrder();
        userRaffleOrderReq.setUserId(partakeRaffleActivityEntity.getUserId());
        userRaffleOrderReq.setActivityId(partakeRaffleActivityEntity.getActivityId());
        UserRaffleOrder userRaffleOrderRes = userRaffleOrderDao.queryNoUsedRaffleOrder(userRaffleOrderReq);
        if (null == userRaffleOrderRes) return null;
        // 封装结果
        UserRaffleOrderEntity userRaffleOrderEntity = new UserRaffleOrderEntity();
        userRaffleOrderEntity.setUserId(userRaffleOrderRes.getUserId());
        userRaffleOrderEntity.setActivityId(userRaffleOrderRes.getActivityId());
        userRaffleOrderEntity.setActivityName(userRaffleOrderRes.getActivityName());
        userRaffleOrderEntity.setStrategyId(userRaffleOrderRes.getStrategyId());
        userRaffleOrderEntity.setOrderId(userRaffleOrderRes.getOrderId());
        userRaffleOrderEntity.setOrderTime(userRaffleOrderRes.getOrderTime());
        userRaffleOrderEntity.setOrderState(userRaffleOrderStateVO.valueOf(userRaffleOrderRes.getOrderState()));
        return userRaffleOrderEntity;

    }

    @Override
    public ActivityAccountEntity queryActivityAccountByUserId(String userId, Long activityId) {
         // 1. 查询账户
        RaffleActivityAccount raffleActivityAccountReq = new RaffleActivityAccount();
        raffleActivityAccountReq.setUserId(userId);
        raffleActivityAccountReq.setActivityId(activityId);
        RaffleActivityAccount raffleActivityAccountRes = raffleActivityAccountDao.queryActivityAccountByUserId(raffleActivityAccountReq);
        if (null == raffleActivityAccountRes) return null;
        // 2. 转换对象
        return ActivityAccountEntity.builder()
                .userId(raffleActivityAccountRes.getUserId())
                .activityId(raffleActivityAccountRes.getActivityId())
                .totalCount(raffleActivityAccountRes.getTotalCount())
                .totalCountSurplus(raffleActivityAccountRes.getTotalCountSurplus())
                .dayCount(raffleActivityAccountRes.getDayCount())
                .dayCountSurplus(raffleActivityAccountRes.getDayCountSurplus())
                .monthCount(raffleActivityAccountRes.getMonthCount())
                .monthCountSurplus(raffleActivityAccountRes.getMonthCountSurplus())
                .build();

    }

    @Override
    public ActivityAccountMonthEntity queryActivityAccountMonthByUserId(String userId, Long activityId, String month) {
        // 1. 查询账户
        RaffleActivityAccountMonth raffleActivityAccountMonthReq = new RaffleActivityAccountMonth();
        raffleActivityAccountMonthReq.setUserId(userId);
        raffleActivityAccountMonthReq.setActivityId(activityId);
        raffleActivityAccountMonthReq.setMonth(month);
        RaffleActivityAccountMonth raffleActivityAccountMonthRes = raffleActivityAccountMonthDao.queryActivityAccountMonthByUserId(raffleActivityAccountMonthReq);
        if (null == raffleActivityAccountMonthRes) return null;
        // 2. 转换对象
        return ActivityAccountMonthEntity.builder()
                .userId(raffleActivityAccountMonthRes.getUserId())
                .activityId(raffleActivityAccountMonthRes.getActivityId())
                .month(raffleActivityAccountMonthRes.getMonth())
                .monthCount(raffleActivityAccountMonthRes.getMonthCount())
                .monthCountSurplus(raffleActivityAccountMonthRes.getMonthCountSurplus())
                .build();

    }

    @Override
    public ActivityAccountDayEntity queryActivityAccountDayByUserId(String userId, Long activityId, String day) {
        // 1. 查询账户
        RaffleActivityAccountDay raffleActivityAccountDayReq = new RaffleActivityAccountDay();
        raffleActivityAccountDayReq.setUserId(userId);
        raffleActivityAccountDayReq.setActivityId(activityId);
        raffleActivityAccountDayReq.setDay(day);
        RaffleActivityAccountDay raffleActivityAccountDayRes = raffleActivityAccountDayDao.queryActivityAccountDay(raffleActivityAccountDayReq);
        if (null == raffleActivityAccountDayRes) return null;
        // 2. 转换对象
        return ActivityAccountDayEntity.builder()
                .userId(raffleActivityAccountDayRes.getUserId())
                .activityId(raffleActivityAccountDayRes.getActivityId())
                .day(raffleActivityAccountDayRes.getDay())
                .dayCount(raffleActivityAccountDayRes.getDayCount())
                .dayCountSurplus(raffleActivityAccountDayRes.getDayCountSurplus())
                .build();

    }

    @Override
    public List<ActivitySkuEntity> queryActivitySkuByActivityId(Long activityId) {
        List<RaffleActivitySku> raffleActivitySkus = raffleActivitySkuDao.queryActivitySkuByActivityId(activityId);
        List<ActivitySkuEntity> activitySkuEntities = new ArrayList<>();
        for (RaffleActivitySku raffleActivitySku:raffleActivitySkus ) {
            ActivitySkuEntity activitySkuEntity = new ActivitySkuEntity();
             activitySkuEntity.setSku(raffleActivitySku.getSku());
             activitySkuEntity.setActivityId(raffleActivitySku.getActivityId());
             activitySkuEntity.setActivityCountId(raffleActivitySku.getActivityCountId());
             activitySkuEntity.setStockCount(raffleActivitySku.getStockCount());
             activitySkuEntity.setStockCountSurplus(raffleActivitySku.getStockCountSurplus());
            activitySkuEntities.add(activitySkuEntity);
        }
        return activitySkuEntities;
    }

    @Override
    public ActivityAccountEntity queryActivityAccountEntity(Long activityId, String userId) {

        RaffleActivityAccount raffleActivityAccount = raffleActivityAccountDao.queryActivityAccountByUserId(RaffleActivityAccount.builder()
                .activityId(activityId)
                .userId(userId)
                .build());
        ActivityAccountEntity activityAccountEntity = new ActivityAccountEntity();
         activityAccountEntity.setUserId(raffleActivityAccount.getUserId());
         activityAccountEntity.setActivityId(raffleActivityAccount.getActivityId());
         activityAccountEntity.setTotalCount(raffleActivityAccount.getTotalCount());
         activityAccountEntity.setTotalCountSurplus(raffleActivityAccount.getTotalCountSurplus());
         activityAccountEntity.setDayCount(raffleActivityAccount.getDayCount());
         activityAccountEntity.setDayCountSurplus(raffleActivityAccount.getDayCountSurplus());
         activityAccountEntity.setMonthCount(raffleActivityAccount.getMonthCount());
         activityAccountEntity.setMonthCountSurplus(raffleActivityAccount.getMonthCountSurplus());

        return activityAccountEntity;
    }

    @Override
    public Integer queryRaffleActivityAccountPartakeCount(Long activityId, String userId) {
        RaffleActivityAccount raffleActivityAccount = raffleActivityAccountDao.queryActivityAccountByUserId(RaffleActivityAccount.builder()
                .userId(userId)
                .activityId(activityId)
                .build());
        return raffleActivityAccount.getTotalCount()-raffleActivityAccount.getTotalCountSurplus();

    }


}
